#include <string>
#include <iostream>
#include "messages/AlarmAction.h"
#include "../plugins/jsoncpp1.9.0/json.h"
class AlarmAction {
public:
    std::string toJson(const AlarmModel& alarmModel) {
        Json::Value root;
        root["code"] = alarmModel.code;
        root["pages"] = alarmModel.pages;
        root["total"] = alarmModel.total;

        Json::Value data(Json::arrayValue);
        for (const auto& item : alarmModel.data) {
            Json::Value itemJson;
            itemJson["id"] = item.id;
            itemJson["source"] = item.source;
            itemJson["type"] = item.type;
            itemJson["code"] = item.code;
            itemJson["timestamp"] = item.timestamp;
            itemJson["level"] = item.level;
            itemJson["info"] = item.info;
            data.append(itemJson);
        }
        root["data"] = data;

        Json::StreamWriterBuilder jswBuilder;
        jswBuilder["emitUTF8"] = true;
        std::unique_ptr<Json::StreamWriter>jsWriter(jswBuilder.newStreamWriter());

        std::ostringstream os;
        jsWriter->write(root, &os);
        return os.str();
    }
    AlarmModel fromJson(const std::string& jsonStr) {
        Json::Value root;
        Json::CharReaderBuilder builder;
        std::istringstream iss(jsonStr);
        std::string errs;
        if (!Json::parseFromStream(builder, iss, &root, &errs)) {
            throw std::runtime_error("Failed to parse JSON: " + errs);
        }

        AlarmModel alarmModel;
        alarmModel.code = root["code"].asInt();
        alarmModel.pages = root["pages"].asInt();
        alarmModel.total = root["total"].asInt();

        const Json::Value data = root["data"];
        for (const auto& itemJson : data) {
            AlarmItem item;
            item.id = itemJson["id"].asInt();
            item.source = itemJson["source"].asString();
            item.type = itemJson["type"].asString();
            item.code = itemJson["code"].asString();
            item.timestamp = itemJson["timestamp"].asString();
            item.level = itemJson["level"].asString();
            item.info = itemJson["info"].asString();
            alarmModel.data.push_back(item);
        }

        return alarmModel;
    }
};